<?php

namespace app\index\controller;



use app\data\model\DataArticleCate;
use app\data\model\GoodsAttributeRelations;
use app\data\model\GoodsAttributeValue;
use app\data\model\GoodsModels;

use app\data\model\StoreCart;

use app\data\model\StoreGoods;

use app\data\model\storeOrder;

use app\data\model\storeOrderGoods;

use app\index\controller\Custom;

use think\admin\Controller;

use think\facade\Db;

use think\facade\Route;



/**

 * 产品入口

 * Class Index

 * @package app\index\controller

 */

class Product extends Base

{



    public function initialize()

    {

        //检测用户登陆状态

        $userID = $this->app->session->get('uid');

        $userInfo = $this->app->db->name('DataUser')->where('id', $userID)->find();

        $this->assign('userInfo', $userInfo);

        $this->assign('is_login',$this->app->session->get('uid') ? true : false);



        /* 定义全局函数 */

        $GLOBALS['function'] = new \app\index\controller\Custom($this->app);

        $this->assign('function', new \app\index\controller\Custom($this->app));



        /* 定义商城全局函数 */

        $GLOBALS['shop'] = new \app\index\controller\Customshop($this->app);

        $this->assign('shop', new \app\index\controller\Customshop($this->app));





        $config = $GLOBALS['function']->getConfig();      //获得网站配置

        $this->assign('config', $config);



        //加载语言包

        $langGet = $this->request->param('lang');

        if (empty($langGet)) {

            $this->app->session->set('lang', 'cn');

        } else {

            $this->app->session->set('lang', $langGet);

        }

        $lang = [];

        $langSession = $this->app->session->get('lang');

        include "public/lang/files/" . $langSession . ".php";

        $this->assign('lang', $lang);

        $this->assign('langSession', $langSession);



        //获取语言包列表

        $files = scandir($_SERVER["DOCUMENT_ROOT"] . "/public/lang/files/");

        $LanguageFilesList = [];

        // 读取指定目录下的所有文件

        foreach ($files as $key => $value) {

            if ($value == "." || $value == "..") {

            } else {

                $languageName = substr($value, 0, strrpos($value, "."));

                $LanguageFilesList[$key] = $languageName;

            }

        }

        $LanguageFilesList = array_values($LanguageFilesList);

        $this->assign('languagesList', $LanguageFilesList);



        //顶部自定义导航

        $nav = $GLOBALS['function']->getAllCat();      //获得网站导航

        $this->assign('nav', $nav);



        /*Banner轮播图*/

        $bannerArr = $GLOBALS['function']->sliderPictures(4);   //sliderPictures()里的数值去查看system_data数据表里name为对应位置，如首页轮播sliderHomePage所在的id

        $this->assign('banner', $bannerArr);



        //获得内容模型列表(用于搜索功能)

        $this->assign('modelList', $GLOBALS['function']->getModelList());



        $id = $this->request->param('id');

        $id = empty($id) ? 0 : $id;

        $this->assign('catId', $id);

        $articleCate = DB::name('DataArticleCate')->where(["id" => $id])->find();  //分类信息

        $this->assign('catInfo', $articleCate);     //当前分类信息

      

    }



    //产品列表

    public function list(){

        return $this->fetch();

    }



    public function detail(){

        $this->check_login();

        $goods_id = $this->request->param('goods_id');



        // 获取商品详情及其关联的型号

        $this->goods_detail = StoreGoods::with(['models'])->where('id', $goods_id)->find();
        
        $this->goods_detail['slides'] = explode('|',$this->goods_detail['image']);
        
        // 检查是否获取到商品并且是否有型号

        if ($this->goods_detail &&  !empty($this->goods_detail->models) && count($this->goods_detail->models)) {

            $models_first_goods = $this->goods_detail->models[0]; // 获取第一个型号

        

            // 获取该型号的详细信息

            $models_first = GoodsModels::find($models_first_goods->id);

        

            // 先初始化一个数组存储属性

            $model_attributes = [];

        

            // 获取该型号的所有属性

            $attributes = $models_first->attributes()->with(['attribute', 'attribute_value'])->select();

        

            // 遍历属性并处理

            foreach ($attributes as $attribute) {

                // 先初始化一个数组存储当前属性的名称和值

                $attribute_info = [

                    'name'  => $attribute->attribute->name ?? '未知属性', // 属性名称

                    'value' => null, // 属性值

                    'sort'  => 0

                ];

        

                // 判断属性类型并获取值

                if ($attribute->attribute) {

                    if ($attribute->attribute->type === 'input') {

                        $attribute_info['value'] = $attribute->value ?? '未设置'; // 直接取 value

                    } elseif ($attribute->attribute->type === 'select') {

                        $attribute_info['value'] = $attribute->attribute_value->value ?? '未选择'; // 查找对应的选项文本

                    }
                    $attribute_info['sort']   = $attribute->attribute->sort ?? 0;

                }

        

                // 将当前属性信息添加到数组

                $model_attributes[] = $attribute_info;

            }

            if (!empty($model_attributes)) {
                // 遍历数组，确保每个元素都有 sort 字段，如果没有则赋予默认值 0
                $model_attributes = array_map(function ($item) {
                    if (!isset($item['sort'])) {
                        $item['sort'] = 0; // 如果 sort 字段不存在，赋予默认值 0
                    }
                    return $item;
                }, $model_attributes);
    
                // 使用 usort 对数组排序
                usort($model_attributes, function ($a, $b) {
                    return $a['sort'] - $b['sort']; // 根据 sort 字段升序排序
                });
           
            } else {
                // 如果 $model_attributes 为空，可以赋予一个空数组，或者根据需求处理
                $model_attributes = [];
            }

            // 将属性数组放入 $models_first 中，便于渲染

            $models_first->attributes_info = $model_attributes;

        } else {

            // 如果没有找到商品或没有型号，处理异常情况

            $models_first = null;

            $model_attributes = []; // 空数组，防止后续渲染时出错

        }

        $this->models_first = $models_first;

        $this->model_attributes = $model_attributes;

        // dump($this->models_first);die;

        $this->catInfo      = DataArticleCate::where('id',2)->find();

        return $this->fetch();

    }



    //产品详情

    public function goods_spec_detail(){

        $model_id = request()->param('model_id',0);

        if(!$model_id){

            return $this->error('参数缺失');

        }

        // 获取该型号的详细信息

        $models_first = GoodsModels::find($model_id);

        if(!$models_first){

            return $this->error('规格未找到');

        }

        // 先初始化一个数组存储属性

        $model_attributes = [];

    

        // 获取该型号的所有属性

        $attributes = $models_first->attributes()->with(['attribute', 'attribute_value'])->select();

      
       
        // 遍历属性并处理

        foreach ($attributes as $attribute) {

            if($attribute->attribute->type == 'checkbox'){
                $realtions_value = GoodsAttributeRelations::where('model_id',$model_id)->where('attribute_id',$attribute->attribute_id)->value('value');
                $realtions_value_text = GoodsAttributeValue::where('id','in',$realtions_value)->column('value');
                $attribute->attribute_value = is_array($realtions_value_text) ?  implode(',',$realtions_value_text) : [];
            }

            // 先初始化一个数组存储当前属性的名称和值

            $attribute_info = [

                'name'  => $attribute->attribute->name ?? '未知属性', // 属性名称

                'value' => null, // 属性值

                'sort'  => 0

            ];

           

            // 判断属性类型并获取值

            if ($attribute->attribute) {

                if ($attribute->attribute->type === 'input') {

                    $attribute_info['value'] = $attribute->value ?? '未设置'; // 直接取 value

                } elseif ($attribute->attribute->type === 'select') {

                    $attribute_info['value'] = $attribute->attribute_value->value ?? '未选择'; // 查找对应的选项文本

                }elseif ($attribute->attribute->type === 'checkbox') {
                    
                    $attribute_info['value'] =  $attribute->attribute_value ? $attribute->attribute_value : '未选择'; // 查找对应的选项文本

                }
                $attribute_info['sort']   = $attribute->attribute->sort ?? 0;

            }

    

            // 将当前属性信息添加到数组

            $model_attributes[] = $attribute_info;

        }

        if (!empty($model_attributes)) {
            // 遍历数组，确保每个元素都有 sort 字段，如果没有则赋予默认值 0
            $model_attributes = array_map(function ($item) {
                if (!isset($item['sort'])) {
                    $item['sort'] = 0; // 如果 sort 字段不存在，赋予默认值 0
                }
                return $item;
            }, $model_attributes);

            // 使用 usort 对数组排序
            usort($model_attributes, function ($a, $b) {
                return $a['sort'] - $b['sort']; // 根据 sort 字段升序排序
            });
        } else {
            // 如果 $model_attributes 为空，可以赋予一个空数组，或者根据需求处理
            $model_attributes = [];
        }

        // 将属性数组放入 $models_first 中，便于渲染

        $models_first->attributes_info = $model_attributes;

        return $this->success('ok',$models_first);

    }



    //添加购物车

    public function cart_add(){

        $this->check_login();

        if(request()->post()){

            $data = $this->_vali([

                'goods_id.require' => '商品id不能为空!',

                'model_id.require' => '型号不能为空!',

                'cart_num.require' => '数量不能为空!',

            ]);

            Db::startTrans();

            try {

                if(!$goods = StoreGoods::find($data['goods_id'])){

                    throw new \Exception('商品不存在');

                }

                if(!$goods_model = GoodsModels::where('goods_id',$data['goods_id'])->where('id',$data['model_id'])->find()){

                    throw new \Exception('型号不存在');

                }

                $member_id = $this->uid;

   

                $cart = StoreCart::where('member_id', $member_id)

                    ->where('goods_id', $data['goods_id'])

                    ->where('models_id',$data['model_id'])

                    ->find();

                if($cart){

                    $cart->goods_number += $data['cart_num'];

                    $cart->save();

                }else{

                    $cart = StoreCart::create([

                        'goods_id' => $goods->id,

                        'member_id' => $member_id,

                        'models_id' => $goods_model->id,

                        'goods_name' => $goods->title,

                        'models_id'  => $goods_model->id,

                        'goods_logo' => $goods->logo,

                        'goods_number' => $data['cart_num'],

                        'goods_spec' => $goods_model->name,

                        'add_time'  => date('Y-m-d H:i:s')

                    ]);

                }

                Db::commit();

            } catch (\Exception $e) {

                return $this->error($e->getMessage());

                Db::rollback();

            }

            return $this->success('添加成功',['cart_id'=>$cart->id]);

        }else{

            return $this->error('非法请求');

        }

    }



    //下单

    public function sure_orde(){

        $this->check_login();

        if(request()->post()){

            $data = $this->_vali([

                'goods_id.require' => '商品id不能为空!',

                'model_id.require' => '型号不能为空!',

                'cart_num.require' => '数量不能为空!',

            ]);

            Db::startTrans();

            try {

                if(!$goods = StoreGoods::find($data['goods_id'])){

                    throw new \Exception('商品不存在');

                }

                if(!$goods_model = GoodsModels::where('goods_id',$data['goods_id'])->where('id',$data['model_id'])->find()){

                    throw new \Exception('型号不存在');

                }

                $member_id = $this->uid;

   

                $cart = StoreCart::where('member_id', $member_id)

                    ->where('goods_id', $data['goods_id'])

                    ->where('models_id',$data['model_id'])

                    ->find();

                if(!$cart){

                    $cart = StoreCart::create([

                        'goods_id' => $goods->id,

                        'member_id' => $member_id,

                        'goods_name' => $goods->title,

                        'models_id'  => $goods_model->id,

                        'goods_logo' => $goods->logo,

                        'goods_number' => $data['cart_num'],

                        'goods_spec' => $goods_model->name,

                        'add_time'  => date('Y-m-d H:i:s')

                    ]);

                }else{

                    $cart->goods_number = $data['cart_num'];

                    $cart->save();

                }

              

                do{

                    $error = 0;

                    $orderCn = $this->new_order_sn();  //获得新订单号

                    $oCount = StoreOrder::field('COUNT(id) AS o_count')->where('order_no',$orderCn)->find();

                    if($oCount['o_count'] > 0){

                        $error = 1;

                    }

                }while($error == 1);    //如果在订单记录中有重复订单号则重新生成

        

                $data['mid'] = $member_id;

                $data['order_no'] = $orderCn;

                $data['price_total'] = 0; //待付金额，即总金额

                $data['price_goods'] = 0; //商品金额

                $data['price_express'] = 0; //快递金额

                $data['price_discount'] = 0; //优惠

                $data['pay_id'] = 0; //支付方式ID

                $data['pay_type'] = ''; //支付状态

                $data['status'] = 2; //订单状态为待支付状态

                $data['express_address_id'] = 0; //收货地址ID

                $data['express_name'] = $this->user_info['nickname']; //收货人姓名

                $data['express_phone'] = $this->user_info['phone']; //收货人手机

                $data['express_province'] = ''; //收货地址省份

                $data['express_city'] = ''; //收货地址城市

                $data['express_area'] = ''; //收货地址区域

                $data['express_address'] = ''; //收货详细地址

                $data['order_desc'] = ''; //订单备注

                $insert_order = StoreOrder::create($data);

                StoreOrderGoods::create([

                    'uid' => $member_id,

                    'order_id' => $insert_order->id,

                    'goods_id' => $goods->id,

                    'goods_name' => $goods->title,

                    'models_id' => $goods_model->id,

                    'goods_num' => $data['cart_num'],

                    'goods_thumb' => $goods_model->thumb,

                    'spec'  => $goods_model->name,

                    'goods_thumb' => $goods_model->thumb,

                    'cart_ids' => $cart->id

                ]);

                Db::commit();

            } catch (\Exception $e) {

                return $this->error($e->getMessage().$e->getLine());

                Db::rollback();

            }

            return $this->success('添加成功',['cart_id'=>$insert_order->id]);

        }else{

            return $this->error('非法请求');

        }

    }



    //更新购物车

    public function update_cart(){

        $this->check_login();

        if(request()->post()){

            $data = $this->_vali([

                'cart_id.require' => '购物车id不能为空!',

                'cart_num.require' => '数量不能为空!',

            ]);

            $uid = $this->uid;

            if(!$goods_cart = StoreCart::where('member_id',$uid)->where('id',$data['cart_id'])->find()){

                return $this->error('购物车不存在');

            }

            $goods_cart->goods_number = $data['cart_num'];

            if($goods_cart->save()) return $this->success('操作成功');

            return $this->error('操作失败');

        }else{

            return $this->error('非法请求');

        }

    }



    //删除购物车

    public function delete_cart(){

        $this->check_login();

        if(request()->post()){

            return $this->success('操作成功');

            $data = $this->_vali([

                'cart_id.require' => '购物车id不能为空!',

            ]);

            $uid = $this->uid;

            if(!$goods_cart = StoreCart::where('member_id',$uid)->where('id',$data['cart_id'])->find()){

                return $this->error('购物车不存在');

            }

            if($goods_cart->delete()) return $this->success('操作成功');

            return $this->error('操作失败');

        }else{

            return $this->error('非法请求');

        }

    }



    //购物车提交订单

    public function submit_cart_order() {

        $this->check_login();

    

        if (request()->post()) {

            $data = $this->_vali([

                'cart_ids.require' => '购物车ID不能为空!',

            ]);

         

            Db::startTrans();

            try {

                $cartIds = explode(',', $data['cart_ids']); // 分割 cart_ids，获取数组

                $member_id = $this->uid;

    

                // 初始化订单总价

                $totalPrice = 0;

                $totalGoodsPrice = 0;

                $totalExpressPrice = 0; // 如果有快递费用，可以加上

    

                // 存储订单商品数据

                $orderGoods = [];

    

                // 获取购物车信息

                $cartItems = StoreCart::where('id', 'in',$cartIds)

                    ->where('member_id', $member_id)

                    ->select();

    

                if (!$cartItems) {

                    throw new \Exception('购物车商品不存在');

                }

               

                // 遍历购物车商品

                foreach ($cartItems as $cart) {

                    $goods = StoreGoods::find($cart->goods_id);

                    $goods_model = GoodsModels::where('goods_id', $cart->goods_id)->where('id', $cart->models_id)->find();

    

                    if (!$goods || !$goods_model) {

                        throw new \Exception('商品或型号不存在');

                    }

    

                    // 计算商品金额

                    $goodsTotalPrice = $goods_model->price * $cart->goods_number;

                    $totalGoodsPrice += $goodsTotalPrice;

    

                    // 将商品加入订单商品列表

                    $orderGoods[] = [

                        'uid' => $member_id,

                        'order_id' => 0, // 初步设置为 0，稍后更新

                        'goods_id' => $goods->id,

                        'goods_name' => $goods->title,

                        'models_id' => $goods_model->id,

                        'goods_num' => $cart->goods_number,

                        'goods_thumb' => $goods_model->thumb,

                        'spec' => $goods_model->name,

                        'cart_ids' => $cart->id,

                    ];

    

                    // 计算运费（可以根据实际情况加上运费计算逻辑）

                    $totalExpressPrice = 0; // 假设暂时没有快递费用

                }

              

    

                // 生成订单号

                do {

                    $error = 0;

                    $orderCn = $this->new_order_sn();  // 获得新订单号

                    $oCount = StoreOrder::field('COUNT(id) AS o_count')->where('order_no', $orderCn)->find();

                    if ($oCount['o_count'] > 0) {

                        $error = 1;

                    }

                } while ($error == 1);    // 如果在订单记录中有重复订单号则重新生成

    

                // 订单数据

                $orderData = [

                    'mid' => $member_id,

                    'order_no' => $orderCn,

                    'price_total' => $totalGoodsPrice + $totalExpressPrice, // 总金额

                    'price_goods' => $totalGoodsPrice, // 商品金额

                    'price_express' => $totalExpressPrice, // 快递金额

                    'price_discount' => 0, // 优惠金额

                    'pay_id' => 0, // 支付方式ID

                    'pay_type' => '', // 支付状态

                    'status' => 2, // 订单状态为待支付状态

                    'express_address_id' => 0, // 收货地址ID

                    'express_name' => $this->user_info['nickname'], // 收货人姓名

                    'express_phone' => $this->user_info['phone'], // 收货人手机

                    'express_province' => '', // 收货地址省份

                    'express_city' => '', // 收货地址城市

                    'express_area' => '', // 收货地址区域

                    'express_address' => '', // 收货详细地址

                    'order_desc' => '', // 订单备注

                ];

               

    

                // 创建订单

                $insert_order = StoreOrder::create($orderData);

    

                // 更新订单商品的订单ID

                foreach ($orderGoods as &$orderItem) {

                    $orderItem['order_id'] = $insert_order->id; // 设置正确的订单ID

                }

                $order_goods_model = new StoreOrderGoods;

                // 批量插入订单商品

                $order_goods_model->saveAll($orderGoods);

    

                // 删除已加入订单的购物车商品

                StoreCart::where('id','in', $cartIds)->where('member_id', $member_id)->delete();

    

                Db::commit();

    

           

            } catch (\Exception $e) {

                Db::rollback();

                return $this->error($e->getMessage() . ' ' . $e->getLine());

            }

            return $this->success('订单提交成功', ['order_id' => $insert_order->id]);

        } else {

            return $this->error('非法请求');

        }

    }



    //批量下单

    public function submit_batch_order() {

       

        $this->check_login();

        if (request()->post()) {

            $data = $this->_vali([

                'items.require' => '产品信息不能为空!',

                'items.array'   => '产品格式不正确!',

            ]);

            $goods_id_arr = $data['items'];

            Db::startTrans();

            try {

                $member_id = $this->uid;

                // 初始化订单总价

                $totalPrice = 0;

                $totalGoodsPrice = 0;

                $totalExpressPrice = 0; // 如果有快递费用，可以加上

    

                // 存储订单商品数据

                $orderGoods = [];



               

                // 遍历购物车商品

                foreach ($goods_id_arr as $cart) {

                    $goods = StoreGoods::find($cart['goods_id']);

                    $goods_model = GoodsModels::where('goods_id', $cart['goods_id'])->where('id', $cart['model_id'])->find();

    

                    if (!$goods || !$goods_model) {

                        throw new \Exception('商品或型号不存在');

                    }

    

                    // 计算商品金额

                    $goodsTotalPrice = $goods_model->price * $cart['cart_num'];

                    $totalGoodsPrice += $goodsTotalPrice;

    

                    // 将商品加入订单商品列表

                    $orderGoods[] = [

                        'uid'         => $member_id,

                        'order_id'    => 0, // 初步设置为 0，稍后更新

                        'goods_id'    => $goods->id,

                        'goods_name'  => $goods->title,

                        'models_id'   => $goods_model->id,

                        'goods_num'   => $cart['cart_num'],

                        'goods_thumb' => $goods_model->thumb,

                        'spec'        => $goods_model->name

                    ];

    

                    // 计算运费（可以根据实际情况加上运费计算逻辑）

                    $totalExpressPrice = 0; // 假设暂时没有快递费用

                }

              

    

                // 生成订单号

                do {

                    $error = 0;

                    $orderCn = $this->new_order_sn();  // 获得新订单号

                    $oCount = StoreOrder::field('COUNT(id) AS o_count')->where('order_no', $orderCn)->find();

                    if ($oCount['o_count'] > 0) {

                        $error = 1;

                    }

                } while ($error == 1);    // 如果在订单记录中有重复订单号则重新生成

    

                // 订单数据

                $orderData = [

                    'mid'                => $member_id,

                    'order_no'           => $orderCn,

                    'price_total'        => $totalGoodsPrice + $totalExpressPrice, // 总金额

                    'price_goods'        => $totalGoodsPrice, // 商品金额

                    'price_express'      => $totalExpressPrice, // 快递金额

                    'price_discount'     => 0, // 优惠金额

                    'pay_id'             => 0, // 支付方式ID

                    'pay_type'           => '', // 支付状态

                    'status'             => 2, // 订单状态为待支付状态

                    'express_address_id' => 0, // 收货地址ID

                    'express_name'       => $this->user_info['nickname'], // 收货人姓名

                    'express_phone'      => $this->user_info['phone'], // 收货人手机

                    'express_province'   => '', // 收货地址省份

                    'express_city'       => '', // 收货地址城市

                    'express_area'       => '', // 收货地址区域

                    'express_address'    => '', // 收货详细地址

                    'order_desc'         => '', // 订单备注

                ];



                // 创建订单

                $insert_order = StoreOrder::create($orderData);

                // 更新订单商品的订单ID

                foreach ($orderGoods as &$orderItem) {

                    $orderItem['order_id'] = $insert_order->id; // 设置正确的订单ID

                }

                $order_goods_model = new StoreOrderGoods;

                // 批量插入订单商品

                $order_goods_model->saveAll($orderGoods);

                Db::commit();          

            } catch (\Exception $e) {

                Db::rollback();

                return $this->error($e->getMessage() . ' ' . $e->getLine());

            }

            return $this->success('订单提交成功', ['order_id' => $insert_order->id]);

        } else {

            return $this->error('非法请求');

        }

    }

    

}

